from info import sr
from info.constants import HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.modules.home import home_blu
from flask import current_app, render_template, session, request, jsonify, abort

from info.utils.response_code import RET, error_map


# 新闻首页
@home_blu.route('/')  # 使用蓝图对象来注册路由
def index():
    # 判断用户是否登录
    user_id = session.get('user_id')
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except BaseException as e:
            current_app.logger.error(e)

    user = user.to_dict() if user else None



    # 查询点击量前１０的新闻数据，传入模板
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(HOME_PAGE_MAX_NEWS).all()
    except BaseException as e:
        current_app.logger.error(e)

    news_list = [news.to_dict() for news in news_list]



    # 查询所有分类数据
    try:
        categories = Category.query.all()

    except BaseException as e:
        current_app.logger.error(e)
        return abort(500)

    # 使用后端渲染来展示首页　将数据传入木板渲染
    return render_template('news/index.html', news_list=news_list, categories=categories, user=user)

# 设置网站小图标
@home_blu.route('/favicon.ico')
def favicon():
    # 浏览器会自动发起/favicon.ico请求, 向服务器获取图标, 但是只发起一次
    # 只需要实现该路由, 并且返回图标对应的图片即可

    # flask中封装了获取静态文件的方法  相对路径基于static文件夹
    return current_app.send_static_file("news/favicon.ico")


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid')
    cur_page = request.args.get('cur_page')
    per_count = request.args.get('per_count', HOME_PAGE_MAX_NEWS)

    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 判断分类是否为＇最新＇
    filter_list = [News.status == 0]
    if cid != 1:
        filter_list.append(News.category_id == cid)

    # 按照发布时间　分类　页码　查询新闻数据
    pn = None
    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
    except BaseException as e:
        current_app.logger.error(e)

    data = {
        'news_list': [news.to_dict() for news in pn.items] if pn else[],
        'total_page': pn.pages
    }

    # json　返回数据
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)


